import tkinter as tk
from tkinter import messagebox
import sys
import os
from PIL import Image, ImageTk

class TrayIcon:
    def __init__(self, root, main_window):
        self.root = root
        self.main_window = main_window
        self.icon_path = os.path.join(os.path.dirname(__file__), "icon.png")
        
        # 创建托盘图标
        self.create_tray_icon()
        
        # 创建托盘菜单
        self.create_tray_menu()
    
    def create_tray_icon(self):
        # 创建托盘图标
        if os.path.exists(self.icon_path):
            self.icon = Image.open(self.icon_path)
            self.icon = self.icon.resize((20, 20), Image.LANCZOS)
            self.icon = ImageTk.PhotoImage(self.icon)
        else:
            # 使用默认图标
            self.icon = tk.PhotoImage(width=20, height=20)
        
        # 创建托盘
        self.tray = tk.Tk()
        self.tray.withdraw()
        self.tray.iconphoto(True, self.icon)
        self.tray.protocol("WM_DELETE_WINDOW", self.minimize_to_tray)
        
        # 用于托盘的隐藏窗口
        self.tray_window = tk.Toplevel(self.tray)
        self.tray_window.withdraw()
    
    def create_tray_menu(self):
        # 创建托盘菜单
        self.menu = tk.Menu(self.tray, tearoff=0)
        self.menu.add_command(label="Show", command=self.show_main_window)
        self.menu.add_command(label="Exit", command=self.exit_app)
        
        # 创建托盘
        self.tray.iconbitmap(default=self.icon)
        self.tray.menu = self.menu
        self.tray.tray_icon = self.icon
    
    def minimize_to_tray(self):
        self.root.withdraw()
        self.tray.deiconify()
    
    def show_main_window(self):
        self.tray.withdraw()
        self.root.deiconify()
        self.root.lift()
    
    def exit_app(self):
        self.root.destroy()
        self.tray.destroy()
        sys.exit(0)